[deps.host]
gcc4

[deps]
kernel-tarball
grsec

[build]
LINUX_VER=$(cat "$K"/kernel.version)
GRSEC_VER=$(cat "$K"/grsecurity.version)

rm -rf linux-"$LINUX_VER" || true
tar xf "$C"/linux-"$LINUX_VER".tar.xz
cd linux-"$LINUX_VER"

# get into menuconfig using
# make HOSTCFLAGS="-D_GNU_SOURCE" HOSTLDFLAGS=-lncurses menuconfig

dopatch() {
	echo "applying patch $1"
	if ! patch -p1 < "$1" ; then
		echo "patch failed!"
		exit 1
	fi
}

#noperl and qemu patches from landley.net/aboriginal
dopatch "$K"/linux-noperl-timeconst.patch

# work around mismatch between devicename and channel name in 9p virtfs code
# p9_virtio_create gets something like "/dev/chan" and the channel name is "chan"
dopatch "$K"/linux-virtio9p.patch

# patches to support busybox trap and sed with strict musl BRE engine
dopatch "$K"/linux-3.8-trap.patch
dopatch "$K"/linux-3.18-posix_sed.patch
dopatch "$K"/linux-3.18-posix_sh.patch

if [ -n "$ENABLE_GRSEC" ] ; then
	patchname="$GRSEC_VER".patch
	xzcat "$C"/"$patchname".xz > "$patchname"
	ln -sf "$patchname" grsec.patch
	dopatch grsec.patch
fi

export ARCH=$A
linux_config="$K"/linux.config

if [ -z "$HOSTCC" ] ; then
	HOSTCC="$CC"
fi

if [ "$A" = arm ] ; then
	[ -z "$ARM_ARCH" ] && (echo "error: need to set ARM_ARCH to 4-7" ; exit 1)
	linux_config="$linux_config $K/linux.config.armv${ARM_ARCH}l"
fi

cat "$linux_config" > my.config

make V=1 ARCH=$A allnoconfig HOSTCFLAGS="-D_GNU_SOURCE" \
  KCONFIG_ALLCONFIG=my.config DISABLE_PAX_PLUGINS=y

#let make create dependencies, otherwise parallel build wont work
make v=1 CC="$CC" HOSTCC="$HOSTCC" ARCH=$A HOSTCFLAGS=-D_GNU_SOURCE \
  DISABLE_PAX_PLUGINS=y dep

make V=1 -j$MAKE_THREADS CC="$CC" ARCH=$A HOSTCC="$HOSTCC" \
  HOSTCFLAGS=-D_GNU_SOURCE DISABLE_PAX_PLUGINS=y

make INSTALL_MOD_PATH=$butch_root_dir DISABLE_PAX_PLUGINS=y modules_install

mkdir -p $butch_root_dir/boot $butch_root_dir/lib/modules $butch_root_dir/lib/firmware
cp System.map $butch_root_dir/boot/

if [ "$A" = arm ] ; then
	kpath="arch/arm/boot/zImage"
else
	kpath="arch/x86/boot/bzImage"
fi
cp $kpath $butch_root_dir/boot/vmlinuz

# "build" headers into dest/
# we need to build them after the kernel because grsec assumes this order
# otherwise some generated headers won't be found
make V=1 ARCH=$A HOSTCFLAGS=-D_GNU_SOURCE INSTALL_HDR_PATH=dest \
  DISABLE_PAX_PLUGINS=y headers_install

# remove junk from kernel headers
find dest/include \( -name .install -o -name ..install.cmd \) -delete


exit 0
